﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using UCNKompetenceBors.Database;

namespace UCNKompetenceBors.Admin
{
    public partial class adminCreateUser : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ckeditorBiography.Width = 450;
                this.Form.DefaultButton = btnCreateUser.UniqueID;

                BindRoleDropdown();
                BindSubMenu();
                lblConfirmCreatedUser.Visible = false;
                
                #region Globalization
                string culture = String.Empty;

                if (HttpContext.Current.Session["MyCulture"] != null)
                    culture = HttpContext.Current.Session["MyCulture"].ToString();

                if (!String.IsNullOrEmpty(culture))
                    GeneralTools.SetCulture(culture);

                LocalizeControls();
                #endregion
            }
        }

        /// <summary>
        /// Binds the sub menu links.
        /// </summary>
        private void BindSubMenu()
        {
            hyLinkAdminDashboard.NavigateUrl = "~/Admin/admin.aspx";
            hyLinkUserHandling.NavigateUrl = "~/Admin/adminUsers.aspx";
            hyLinkCreateUser.NavigateUrl = "~/Admin/adminUsersCreate.aspx";
            hyLinkAdminExchange.NavigateUrl = "~/Admin/adminExchange.aspx";
            hyLinkNewsHandling.NavigateUrl = "~/Admin/adminNews.aspx";
            hyLinkEditInformation.NavigateUrl = "~/Admin/adminInformation.aspx";
            hyLinkContactPerson.NavigateUrl = "~/Admin/adminContactPerson.aspx";
            hylinkDepartment.NavigateUrl = "~/Admin/adminDepartment.aspx";
            hyLinkResetUsers.NavigateUrl = "~/Admin/adminUsersReset.aspx";
        }

        /// <summary>
        /// Adds additional profile information to an already existing user, based on the input parameters.
        /// </summary>
        /// <param name="userName">Specifies the user name to be used.</param>
        /// <param name="firstName">Specifies the first name to be used.</param>
        /// <param name="lastName">Specifies the last name to be used.</param>
        /// <param name="phone">Specifies the phone to be used.</param>
        /// <param name="bio">Specifies the biography to be used.</param>
        private void AddAdditionalInfo(string userName, string firstName, string lastName, string phone, string bio)
        {
            dbAdmin.AddProfileInformation(userName, firstName, lastName, phone, bio);
        }

        /// <summary>
        /// Clears controls.
        /// </summary>
        private void ClearControls()
        {
            ckeditorBiography.Text = String.Empty;
            txtConfirmPassword.Text = String.Empty;
            txtEmail.Text = String.Empty;
            txtFirstName.Text = String.Empty;
            txtLastName.Text = String.Empty;
            txtPassword.Text = String.Empty;
            txtPhone.Text = String.Empty;
            txtUserName.Text = String.Empty;
        }

        private void BindRoleDropdown()
        {
            ddlUserRole.Items.Clear();
            ddlUserRole.Items.Add(new ListItem(GetLocalResourceObject("ddlUserRoleText").ToString(), "Vælg Rolle"));
            ddlUserRole.Items.Add(new ListItem(GetLocalResourceObject("roleUserText").ToString(), "user"));
            ddlUserRole.Items.Add(new ListItem(GetLocalResourceObject("roleAdminText").ToString(), "administrator"));
        }

        protected void btnCreateUser_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                lblConfirmCreatedUser.Visible = true;
                Membership.CreateUser(txtUserName.Text, txtPassword.Text, txtEmail.Text);

                Roles.AddUserToRole(txtUserName.Text, ddlUserRole.SelectedValue.ToString());

                AddAdditionalInfo(txtUserName.Text, txtFirstName.Text, txtLastName.Text, txtPhone.Text, ckeditorBiography.Text);

                ClearControls();
            }
        }

        /// <summary>
        /// Checks whether or not the username is valid, based on the userName parameter.
        /// </summary>
        /// <param name="userName">Specifies the user name to be used</param>
        /// <returns>Returns a boolean specifying whether or not the user name is valid</returns>
        private bool ValidateUsername(string userName)
        {
            return (Membership.GetUser(userName) != null);
        }

        //Event fired when the custom validator validates on the server
        protected void cusvalUserName_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (ValidateUsername(txtUserName.Text))
            {
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }

        //Event fired when the custom validator validates on the server
        protected void cusvalEmail_ServerValidate(object source, ServerValidateEventArgs args)
        {
            string username = Membership.GetUserNameByEmail(txtEmail.Text);
            if (!String.IsNullOrEmpty(username))
            {
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }

        /// <summary>
        /// Localizes the controls of the site, based on the current UI Culture.
        /// </summary>
        private void LocalizeControls()
        {
            hyLinkAdminDashboard.Text = GetLocalResourceObject("hyLinkAdminDashboardText").ToString();
            hyLinkUserHandling.Text = GetLocalResourceObject("hyLinkUserHandlingText").ToString();
            hyLinkAdminExchange.Text = GetLocalResourceObject("hyLinkAdminExchangeText").ToString();
            hyLinkNewsHandling.Text = GetLocalResourceObject("hyLinkNewsHandlingText").ToString();
            hyLinkEditInformation.Text = GetLocalResourceObject("hyLinkEditInformationText").ToString();
            hyLinkResetUsers.Text = GetLocalResourceObject("hyLinkResetUsersText").ToString();
            hyLinkContactPerson.Text = GetLocalResourceObject("hyLinkContactPersonText").ToString();
            hylinkDepartment.Text = GetLocalResourceObject("hylinkDepartmentText").ToString();
            hyLinkCreateUser.Text = GetLocalResourceObject("hyLinkCreateUserText").ToString();

            lblAdditionalInfo.Text = GetLocalResourceObject("lblAdditionalInfoText").ToString();
            lblBiography.Text = GetLocalResourceObject("lblBiographyText").ToString();
            lblConfirmPassword.Text = GetLocalResourceObject("lblConfirmPasswordText").ToString();
            lblCreateUserHeader.Text = GetLocalResourceObject("lblCreateUserHeaderText").ToString();
            lblEmail.Text = GetLocalResourceObject("lblEmailText").ToString();
            lblFirstName.Text = GetLocalResourceObject("lblFirstNameText").ToString();
            lblLastName.Text = GetLocalResourceObject("lblLastNameText").ToString();
            lblPassword.Text = GetLocalResourceObject("lblPasswordText").ToString();
            lblPhone.Text = GetLocalResourceObject("lblPhoneText").ToString();
            lblUserName.Text = GetLocalResourceObject("lblUserNameText").ToString();
            lblUserRole.Text = GetLocalResourceObject("lblUserRoleText").ToString();
            lblConfirmCreatedUser.Text = GetLocalResourceObject("lblConfirmCreatedUserText").ToString();

            ddlUserRole.Items[0].Text = GetLocalResourceObject("ddlUserRoleText").ToString();

            string regexMailValidation = GetLocalResourceObject("regexvalEmailText").ToString();
            regexvalEmail.ToolTip = regexMailValidation;
            regexvalEmail.ErrorMessage = regexMailValidation;

            string cusvalMailValidation = GetLocalResourceObject("cusvalEmailText").ToString();
            cusvalEmail.ToolTip = cusvalMailValidation;
            cusvalEmail.ErrorMessage = cusvalMailValidation;


            string passwordStrengthValidation = GetLocalResourceObject("regexvalPasswordStrengthText").ToString();
            regexvalPasswordStrength.ToolTip = passwordStrengthValidation;
            regexvalPasswordStrength.ErrorMessage = passwordStrengthValidation;

            string phoneValidation = GetLocalResourceObject("regexvalPhoneText").ToString();
            regexvalPhone.ToolTip = phoneValidation;
            regexvalPhone.ErrorMessage = phoneValidation;

            string comparePassValidation = GetLocalResourceObject("compvalConfirmPasswordText").ToString();
            compvalConfirmPassword.ToolTip = phoneValidation;
            compvalConfirmPassword.ErrorMessage = phoneValidation;

            string confirmPassValidation = GetLocalResourceObject("rfvalConfirmPasswordText").ToString();
            rfvalConfirmPassword.ToolTip = confirmPassValidation;
            rfvalConfirmPassword.ErrorMessage = confirmPassValidation;

            string mailValidation = GetLocalResourceObject("rfvalEmailText").ToString();
            rfvalEmail.ToolTip = mailValidation;
            rfvalEmail.ErrorMessage = mailValidation;

            string fNameValidation = GetLocalResourceObject("rfvalFirstNameText").ToString();
            rfvalFirstName.ToolTip = fNameValidation;
            rfvalFirstName.ErrorMessage = fNameValidation;

            string lNameValidation = GetLocalResourceObject("rfvalLastNameText").ToString();
            rfvalLastName.ToolTip = lNameValidation;
            rfvalLastName.ErrorMessage = lNameValidation;

            string passwordValidation = GetLocalResourceObject("rfvalPasswordText").ToString();
            rfvalPassword.ToolTip = passwordValidation;
            rfvalPassword.ErrorMessage = passwordValidation;

            string userNameValidation = GetLocalResourceObject("rfvalUserNameText").ToString();
            rfvalUserName.ToolTip = userNameValidation;
            rfvalUserName.ErrorMessage = userNameValidation;

            string userRoleValidation = GetLocalResourceObject("rfvalUserRoleText").ToString();
            rfvalUserRole.ToolTip = userRoleValidation;
            rfvalUserRole.ErrorMessage = userRoleValidation;

            valsumSignupForm.HeaderText = GetLocalResourceObject("valsumSignupFormText").ToString();

            btnCreateUser.Text = GetLocalResourceObject("btnCreateUserText").ToString();

            string culture = String.Empty;

            if (HttpContext.Current.Session["MyCulture"] != null)
                culture = HttpContext.Current.Session["MyCulture"].ToString();

            if (culture.Equals("en-GB"))
                ckeditorBiography.Language = "en";
            else
                ckeditorBiography.Language = "da";

            BindRoleDropdown();
        }
    }
}